<template>
  <div class='search'>
    <van-nav-bar title="搜索商品" left-text="" left-arrow @click-left="$router.go(-1)" />
    <van-search v-model="search" shape="round" background="#EDEDED" placeholder="请输入商品名称" show-action @input="onInput">
      <template #action>
        <span @click="onSearch">搜索</span>
      </template>
    </van-search>

    <div class="search_list">
      <div v-if="showRecord" class="record">
        <div class="title">
          <span>历史搜索</span>
          <van-icon name="delete-o" @click="clearSearchList" />
        </div>
        <div class="record_list">
          <span class="item" v-for="(item, index) in searchList" :key="index" @click="recordSearch(item)">{{ item }}</span>
          <div v-if="searchList.length == 0" class="not">暂无搜索历史</div>
        </div>
      </div>

      <div class="list">
        <div class="item">
          <van-card v-for="(item, index) in list " :key="index" :desc="item.describe" :title="item.product_name">
            <template #thumb>
              <van-image class="thumb" :src="domain + item.imageurl" fit="cover" @click="openDetail(item)" />
            </template>
            <template #price>
              <div class="price">
                <span>￥</span>
                <span>{{ item.sale_price }}</span>
              </div>
            </template>
            <template #num>
              <van-stepper v-model="item.cart_number" :min="0" theme="round" :show-input="item.cart_number > 0 ? true : false" :show-minus="item.cart_number > 0 ? true : false" disable-input integer @plus="changeNumber(item, '+')" @minus="changeNumber(item, '-')" />
            </template>
          </van-card>
        </div>
      </div>
      <van-empty v-if="empty" description="暂无内容" />
    </div>

    <div class="cart">
      <div class="number">
        <van-badge class="cart_img" :content="cartNum > 0 ? cartNum : null" :max="99">
          <img src="../assets/img/cart.png" @click="showCart">
        </van-badge>
        <div v-if="cartNum" class="sum1" @click="showCart">
          <span><span>￥</span>{{ cartPirce }}</span>
          <span>免配送费</span>
        </div>
        <div v-else class="sum2">未选购商品</div>
      </div>
      <div class="submit" :class="cartNum ? 'is' : 'no'" @click="onSettlement">结算</div>
    </div>

    <van-popup class="popup" v-model="show" position="bottom" round>
      <div class="top">
        <div class="cart_name">餐品详情</div>
        <div class="del" @click="clearCartList">
          <van-icon name="delete-o" />
          <span>清空购物车</span>
        </div>
      </div>

      <!-- 购物车列表 -->
      <div class="cart_list">
        <van-card v-for="( item, index ) in cartList " :key="index" :desc="item.describe" :title="item.product_name">
          <template #thumb>
            <van-image class="thumb" :src="domain + item.imageurl" fit="cover" @click="openDetail(item)" />
          </template>
          <template #price>
            <div class="price">
              <span>￥</span>
              <span>{{ item.sale_price }}</span>
            </div>
          </template>
          <template #num>
            <van-stepper v-model="item.quantity" :min="0" theme="round" :show-input="item.quantity > 0 ? true : false" :show-minus="item.quantity > 0 ? true : false" disable-input integer @plus="changeCartNumber(item, '+')" @minus="changeCartNumber(item, '-')" />
          </template>
        </van-card>
      </div>
    </van-popup>

    <!-- 商品详情 -->
    <van-popup class="product" v-model="productShow" round closeable>
      <img class="thumb" :src="domain + obj.imageurl">
      <div class="obj">
        <div class="pname">{{ obj.product_name }}</div>
        <div class="pdesc">{{ obj.describe }}</div>
        <div class="pricenum">
          <div class="price">
            <span>￥</span>
            <span>{{ obj.sale_price }}</span>
            <span> /份</span>
          </div>
          <van-stepper v-model="obj.cart_number" :min="0" theme="round" :show-input="obj.cart_number > 0 ? true : false" :show-minus="obj.cart_number > 0 ? true : false" disable-input integer @plus="changeNumber(obj, '+')" @minus="changeNumber(obj, '-')" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant';


export default {
  data () {
    return {
      list: [],
      search: '',
      searchList: [],
      cartList: [],
      obj: {},
      cartNum: null,
      cartPirce: null,
      show: false,
      productShow: false,
      empty: false,
      showRecord: true,
    };
  },
  created () {
    this.searchList = this.$store.state.searchList.slice(0, 5)
    this.getCartList()
  },
  watch: {
    search (val) {
      if (!val) {
        this.list = []
      }
    },
  },
  methods: {
    getProductList () {
      this.showRecord = false
      this.$axios.get(this.$api.selectlist, {
        params: {
          product_name: this.search
        }
      }).then(res => {
        if (res.data.code == 1) {
          this.list = res.data.data
          if (this.list.length == 0) this.empty = true
        }
      })
    },
    getCartList () {
      this.$axios.get(this.$api.usercartlist).then(res => {
        if (res.data.code == 1) {
          this.cartList = res.data.data.cart
          this.cartNum = res.data.data.number
          this.cartPirce = res.data.data.amount
          if (this.cartList.length == 0) this.show = false
        }
      })
    },
    onInput (val) {
      if (!val) {
        this.showRecord = true
        this.empty = false
      }
    },
    onSearch () {
      if (this.search) {
        this.searchList.unshift(this.search)
        this.searchList = (Array.from(new Set(this.searchList))).slice(0, 5)
        this.$store.commit('setSearchList', this.searchList)
        this.getProductList()
      }
    },
    recordSearch (val) {
      this.search = val
      this.onSearch()
    },
    clearSearchList () {
      this.searchList = []
      this.$store.commit('setSearchList', this.searchList)
    },
    openDetail (e) {
      this.obj = e
      this.productShow = true
    },
    changeNumber (item, str) {
      let params = {
        product_id: item.product_id,
        quantity: str == '+' ? item.cart_number + 1 : item.cart_number - 1
      }
      let api = null
      if (params.quantity > 0 || params.quantity != "") {
        api = this.$api.usereditcart
      } else {
        api = this.$api.userdelcart
        params = {}
        params.cart_ids = item.cart_id.toString()
      }
      this.$axios.post(api, params).then(res => {
        if (res.data.code == 1) {
          this.getCartList()
          if (str == '+') {
            this.list.forEach(type => {
              if (type.type_id == item.type_id) {
                type.product_list.forEach(pro => {
                  if (pro.product_id == item.product_id) {
                    pro.cart_id = res.data.data
                  }
                });
              }
            });
          }
        } else {
          Toast.fail('操作失败')
          this.list = []
          this.getProductList()
        }
      })
    },
    changeCartNumber (item, str) {
      let params = {
        product_id: item.product_id,
        quantity: str == '+' ? item.quantity + 1 : item.quantity - 1
      }
      let api = null
      if (params.quantity > 0 || params.quantity != "") {
        api = this.$api.usereditcart
      } else {
        api = this.$api.userdelcart
        params = {}
        params.cart_ids = item.cart_id.toString()
      }
      this.$axios.post(api, params).then(res => {
        if (res.data.code == 1) {
          this.getCartList()
          this.getProductList()
        } else {
          Toast.fail('操作失败')
          this.cartList = []
          this.getCartList()
        }
      })
    },
    clearCartList () {
      let cart_ids = this.cartList.map(e => e.cart_id).toString()
      Dialog.confirm({
        message: '确认清空购物车？',
      }).then(() => {
        this.$axios.post(this.$api.userdelcart, { cart_ids }).then(res => {
          if ((res.data.code == 1)) {
            this.list = []
            this.cartList = []
            this.cartNum = null
            this.cartPrice = null
            this.getProductList()
            this.show = false
          } else {
            Toast.fail(res.data.msg)
          }
        })
      }).catch(() => {
        // on cancel
      });
    },
    showCart () {
      if (this.cartNum) {
        this.show = !this.show
      }
    },
    onSettlement () {
      if (this.cartNum) {
        let ids = this.cartList.map(e => e.cart_id).toString()
        this.$router.push({ name: 'settlement', query: { ids } });
      } else {
        return false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.search {
  height: 100%;
  background-color: #fff;

  .van-search {
    height: 54px;

    .van-search__content {
      background-color: #fff;
    }
  }

  .search_list {
    height: calc(100vh - 100px - 80px);
    padding-bottom: 80px;
    overflow-y: auto;

    .record {
      .title {
        display: flex;
        justify-content: space-between;
        margin: 15px 15px 0;
        padding-bottom: 15px;
        border-bottom: 1px solid #F2F2F2;
      }

      .record_list {
        display: flex;
        flex-wrap: wrap;
        padding: 16px;

        .item {
          font-size: 14px;
          padding: 6px 9px;
          margin-left: 10px;
          margin-bottom: 10px;
          border-radius: 6px;
          border: 1px solid #999;
        }

        .not {
          width: 100%;
          color: #5F5F5F;
          font-size: 14px;
          text-align: center
        }
      }
    }

    .list {
      padding: 12px;

      .item {

        .title {
          color: #5F5F5F;
          font-size: 14px;
        }
      }
    }
  }

  .van-card {
    padding: 0;
    background-color: #fff;
    margin-top: 10px;

    .van-card__thumb {
      width: 85px;
      height: 85px;
    }

    .thumb {
      width: 100%;
      height: 100%;
    }

    .van-card__title {
      color: #5F5F5F;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }

    .price {
      color: #DB5310;

      span:nth-child(1) {
        font-size: 12px;
      }

      span:nth-child(2) {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  .van-card:not(:first-child) {
    margin-top: 10px;
  }

  .cart {
    position: absolute;
    bottom: 15px;
    width: calc(100% - 30px);
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 15px;
    padding: 5px;
    border-radius: 50px;
    background-color: #494B4E;
    box-sizing: border-box;
    z-index: 9999;

    .cart_img {
      transform: translate(-20px, -10px);

      img {
        width: 78px;
        height: 78px;
      }

      /deep/ .van-badge {
        background-color: #DB5310;
      }

      /deep/ .van-badge--fixed {
        top: 30px;
        right: 20px;
      }
    }

    .number {
      display: flex;
      align-items: center;

      .sum1,
      .sum2 {
        color: #F3F3F3;
        font-size: 16px;
        transform: translateX(-16px);
      }

      .sum1 {
        display: flex;
        flex-direction: column;

        span:nth-child(1) {
          font-size: 16px;
          font-weight: bold;

          span {
            font-weight: 200;
          }
        }

        span:nth-child(2) {
          font-size: 10px;
        }
      }
    }

    .submit {
      width: 108px;
      height: 46px;
      line-height: 46px;
      color: #fff;
      font-size: 20px;
      text-align: center;
      border-radius: 50px;
    }

    .is {
      background-color: #DB5310;
    }

    .no {
      background-color: #9C9A9A;
    }
  }

  .tov {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }

  .popup {
    height: 50%;
    padding: 16px 16px 86px;
    box-sizing: border-box;

    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;

      .cart_name {
        color: #000;
        font-size: 16px;
        font-weight: bold;
      }

      .del {
        color: #999999;
        font-size: 12px;

        .van-icon {
          margin-right: 4px;
        }
      }
    }

    .cart_list {
      height: 200px;
      overflow-y: auto;
    }
  }

  .product {
    width: 85%;
    border-radius: 6px;
    background-color: transparent;

    /deep/.van-popup__close-icon {
      top: 10px;
      right: 10px;
      padding: 4px;
      border-radius: 50%;
      background-color: #878787;
    }

    .thumb {
      display: block;
      width: 100%;
      height: 272px;
      object-fit: cover;
    }

    .obj {
      background-color: #fff;

      .pname {
        max-height: 55px;
        color: #5f5f5f;
        font-size: 16px;
        font-weight: bold;
        padding: 10px 12px 0;
        margin-bottom: 10px;
        overflow: hidden;
        box-sizing: border-box;
      }

      .pdesc {
        max-height: 95px;
        color: #5f5f5f;
        font-size: 14px;
        padding: 0 12px 10px;
        box-sizing: border-box;
        overflow-y: auto;
      }

      .pricenum {
        display: flex;
        justify-content: space-between;
        padding: 10px 12px;

        .price {
          span:nth-child(1) {
            color: #DB5310;
            font-size: 12px;
          }

          span:nth-child(2) {
            color: #DB5310;
            font-size: 18px;
            font-weight: bold;
          }

          span:nth-child(3) {
            color: #5F5F5F;
            font-size: 12px;
          }
        }
      }
    }
  }

  .van-popup--center {
    top: 45%;
  }
}
</style>
